/*
 * Copyright (c) JiaChaoYang 2023-7-27 MongoPlus版权所有
 * 适度编码益脑，沉迷编码伤身，合理安排时间，享受快乐生活。
 * email: j15030047216@163.com
 * phone: 15030047216
 * weChat: JiaChaoYang_
 */

package com.mongo.plus.demo.controller;

import cn.hutool.core.lang.UUID;
import com.anwen.mongo.conditions.query.LambdaQueryChainWrapper;
import com.anwen.mongo.manager.MongoPlusClient;
import com.anwen.mongo.model.PageResult;
import com.anwen.mongo.service.IService;
import com.anwen.mongo.service.impl.ServiceImpl;
import com.anwen.mongo.toolkit.StringUtils;
import com.mongo.plus.demo.dto.UserDTO;
import com.mongo.plus.demo.entity.User;
import com.mongo.plus.demo.repository.UserRepository;
import com.mongo.plus.demo.service.UserService;
import com.mongodb.MongoCommandException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Description:
 * @BelongsProject: mongo-plus-demo
 * @Version: 1.0
 */
@RestController
@Slf4j
public class UserController extends ServiceImpl<User> implements IService<User> {

    @Resource
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @Resource
    private MongoPlusClient mongoPlusClient;

    @Autowired
    TransactionTemplate mongoTransactionTemplate;

    @GetMapping("/findAllUser1111")
    public Object findAllUser1111(@RequestParam(value = "userName", required = false) String userName) {
//        return userRepository.lambdaQuery().like(StringUtils.isNotBlank(userName), User::getUserName, userName).orderByAsc(User::getCreateTime).list();
//        return userRepository.lambdaAggregate().skip(1).limit(10).list();
        return userRepository.list();
    }


    @GetMapping("/findAllUserByPage")
    public PageResult<User> findAllUser(Integer pageNum, Integer pageSize, @RequestParam(value = "userName", required = false) String userName, @RequestParam(value = "roleName", required = false) String roleName) {
        LambdaQueryChainWrapper<User> queryChainWrapper = userRepository.lambdaQuery().like(StringUtils.isNotBlank(userName), User::getUserName, userName);
        queryChainWrapper.orderByDesc(User::getCreateTime);
        PageResult<User> page = userRepository.page(queryChainWrapper, pageNum, pageSize);
        User user = page.getContentData().get(0);
        page.getContentData().forEach(System.out::println);
        return page;
    }

    @PostMapping("/updateAList")
    public boolean updateAList(@RequestBody User user) {
//        userRepository.lambdaQuery().eq(User::getUserId,1).list();
//        return userRepository.lambdaUpdate().push(User::getAList, user.getAList()).update();
        return true;
    }

    @PostMapping("/addBatchUser")
    public Object addBatchUser(@RequestBody UserDTO userDTO) {

        return userRepository.saveBatch(userDTO.getUserList());
    }

    @GetMapping("/autoAddUser")
    public Object autoAddUser() {
        User user = new User();
        user.setUserName("testUser" + UUID.fastUUID().toString());
        return userRepository.save(user);
    }

    @PostMapping("/retry/updateUserById")
    public Object updateUserWithRetryById(@RequestBody User user) {
        return userService.updateUserWithRetryById(user);
    }

    @PostMapping("/updateUserById")
    public Object updateUserById(@RequestBody User user) {
        return mongoTransactionTemplate.execute(status -> {
            User dbUser = this.userRepository.getById(user.getId());
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            dbUser.setUserName(user.getUserName());
            return userRepository.updateById(dbUser);
        });
    }


    @PostMapping("/updateBatchUserByIds")
    public Object updateBatchUserByIds(@RequestBody UserDTO userDTO) {
        return userRepository.updateBatchByIds(userDTO.getUserList());
    }

    @PostMapping("/saveOrUpdateUser")
    public Object saveOrUpdateUser(@RequestBody User user) {
        return userRepository.saveOrUpdate(user);
    }

    @PostMapping("/saveOrUpdateBatchUser")
    public Object saveOrUpdateBatchUser(@RequestBody UserDTO userDTO) {
        return userRepository.saveOrUpdateBatch(userDTO.getUserList());
    }

//    @Override
//    public void convertValue(Field field, Object obj, Object fieldValue) throws IllegalAccessException {
//
//    }

/*    @PostMapping("/deleteUserByIds")
    @ApiOperation("根据ids删除用户")
    public Object deleteUserByIds(@RequestBody List<String> ids){
        return userRepository.removeBatchByIds(ids);
    }*/
}
